<?php
/**
 * Created by PhpStorm.
 * User: Keter
 * Date: 2016/7/28
 * Time: 20:25
 */

class GetPaiZuList extends ApiRedisBase
{
    protected $paijuLogRedis;

    public function logic()
    {
        $this->checkUser();

        $userPaiZuKey = 'UPZ:' . $this->uid;
        $data = $sort = array();
        $this->paijuLogRedis = $this->redis('paiju_log');

        if ($this->paijuLogRedis->exists($userPaiZuKey)) {
            //获取用户的牌组ID
            $result = $this->paijuLogRedis->lrange($userPaiZuKey, -10, -1);
            if ($result) {
                $result = array_flip(array_flip($result));
                foreach ($result as $key => $paiZuID) {
                    //获取牌局日志KEY
                    $paizuKeys = $this->paijuLogRedis->keys('PJL:' . $paiZuID . '*');
                    if (empty($paizuKeys)) {
                        $this->paijuLogRedis->lrem($userPaiZuKey, $paiZuID);
                    } else {
                        $row = $this->getPaizuInfo($paizuKeys);
                        if ($row) {
                            $row['paiZuID'] = $paiZuID;
                            $data[] = $row;
                            $sort[] = $row['time'];
                        }
                    }
                }
            }
        }

        if ($data) {
            asort($sort, SORT_NUMERIC);
            array_multisort($data, SORT_DESC, $sort);
        }

        $this->returnData('suc_action', $data);
    }

    public function getPaizuInfo($paizuKeys)
    {
        $lastID = max($paizuKeys);
        $arr = array('time', 'roomID', 'uids', 'detail');

        //获取牌局日志信息
        $row = $this->paijuLogRedis->hMget($lastID, $arr);
        $row['uids'] = json_decode($row['uids'], JSON_UNESCAPED_UNICODE);
        $row['users'] = $this->getUserData($row);
        unset($row['uids'], $row['detail']);

        return $row;
    }

    /**
     * 获取用户昵称
     * @param $paizuKeys
     * @param $uids
     * @return array
     */
    public function getUserData($row)
    {
        //获取牌局总分数
        $result = array();
        $row['detail'] = json_decode($row['detail'], true);
        $score = $row['detail']['score'];
        $redis = $this->redis('user_info');

        foreach ($row['uids'] as $key => $uid) {
            $userInfo = $redis->hMget('U:' . $uid, array('nickname'));
            if ($userInfo) {
                $totalScore = isset($scores[$uid]) ? $scores[$uid] : 0;
                $result[$key] = [$userInfo['nickname'], $score[$key][1]];
            } else {
                $result[$key] = [];
            }
        }

        return $result;
    }
}